package com.duowei.diandan.fragment.dialog;

import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatDialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.duowei.diandan.R;
import com.duowei.diandan.db.AppDatabase;
import com.duowei.diandan.db.entry.Auth;
import com.duowei.diandan.util.NetUtils;
import com.duowei.diandan.util.Post6Listener;
import com.duowei.diandan.util.ToastUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class AuthDialogFragment extends AppCompatDialogFragment implements View.OnClickListener {
    private final String mUrl="http://androidwww.wxdw.top:2233/androidauth/ServerSvlt?";
    private Auth mAuth;
    private TextView mTvProbation;
    private long mL2;
    private long mL1;
    private String mDeviceID;
    private ProgressBar mPb;

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    private Date currentDate = new Date();
    private AppDatabase mDb;

    public AuthDialogFragment() {
        // Required empty public constructor
    }

    public static AuthDialogFragment newInstance(Auth auth) {
        Bundle args = new Bundle();
        if(auth!=null){
            args.putSerializable("auth",auth);
        }
        AuthDialogFragment fragment = new AuthDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View inflate = inflater.inflate(R.layout.fragment_auth_dialog, container, false);
        setCancelable(false);
        mDb = AppDatabase.getDatabase();

        mAuth = (Auth) getArguments().getSerializable("auth");
        TextView tvMsg = inflate.findViewById(R.id.tv_msg);
        mTvProbation = inflate.findViewById(R.id.tv_probation);
        mPb = inflate.findViewById(R.id.progressBar);
        inflate.findViewById(R.id.btn1).setOnClickListener(this);
        inflate.findViewById(R.id.btn2).setOnClickListener(this);
        Button btnClose = inflate.findViewById(R.id.btn3);
        btnClose.setOnClickListener(this);
        String androidID = Settings.Secure.getString(getActivity().getContentResolver(), Settings.Secure.ANDROID_ID);
        String serialNumber=android.os.Build.SERIAL;
        mDeviceID = "unknown".equals(serialNumber)?androidID:serialNumber;
        if(mAuth ==null){
            tvMsg.setText("序列号/ID："+ mDeviceID);
        }else{
            try {
                Date closedate = dateFormat.parse(mAuth.getClosedate());
                Date authdate = dateFormat.parse(mAuth.getAuthdate());
                mL1 = currentDate.getTime()-authdate.getTime();
                mL2 = closedate.getTime() - currentDate.getTime();
                if(mL1 <0){
                    tvMsg.setText("序列号/ID："+ mDeviceID +"\n\n您的系统时间有误\n请调回正确时间或联系软件供应商");
                }else if(mL2 >=3*24*60*60*1000&&mL2<=7*24*60*60*1000){
                    tvMsg.setText("序列号/ID："+ mDeviceID +"\n\n试用截止日期："+ dateFormat.format(closedate));
                    new Handler().postDelayed(() -> dismiss(),3000);
                }else if(mL2>7*24*60*60*1000){
                    new Handler().postDelayed(() -> dismiss(),0);
                }else{
                    tvMsg.setText("序列号/ID："+ mDeviceID +"\n\n试用截止日期："+ dateFormat.format(closedate));
                }
                if(mL2>0&&mL1>=0){
                    btnClose.setText("我知道了");
                }else{
                    btnClose.setText("关闭");
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return inflate;
    }

    @Override
    public void onClick(View view) {
        String packageName = getActivity().getPackageName();
        if(view.getId()==R.id.btn1){
            mPb.setVisibility(View.VISIBLE);
            String sql="call prc_androidauth_forever('"+mDeviceID+"','"+packageName+"')|";
            NetUtils.post6(mUrl,sql, Auth.class,new Post6Listener<Auth>() {
                @Override
                public void onFail(Exception e) {
                    getActivity().runOnUiThread(() -> {
                        ToastUtils.show(e+"");
                        mPb.setVisibility(View.GONE);
                    });
                }

                @Override
                public void onSuccess(List<Auth> list) {
                    new Thread(() -> {
//                        mDb.authDao().deleteAll();
//                        mDb.authDao().insert(list);

                        if("1".equals(list.get(0).getIsforver())){
                            getActivity().runOnUiThread(() -> ToastUtils.show("恭喜您，您的软件在此设备己永久授权！"));
                            dismiss();
                        }else{
                            getActivity().runOnUiThread(() -> mTvProbation.setText("授权资料己提交，请通知软件供应商开通后，\n再次点击“永久授权”"));
                        }
                        try {
                            Date closedate = dateFormat.parse(list.get(0).getClosedate());
                            mL2 = closedate.getTime() - currentDate.getTime();
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        getActivity().runOnUiThread(() -> mPb.setVisibility(View.GONE));
                    }).start();
                }
            });
        }else if(view.getId()==R.id.btn2){
            Http_probation(packageName);
        }else if(view.getId()==R.id.btn3){
            if(mL2>0&&mL1>=0){
                dismiss();
            }else{
                getActivity().finish();
            }
        }
    }

    /*开通试用*/
    private void Http_probation(String packageName) {
        mPb.setVisibility(View.VISIBLE);
        String sql="call prc_androidauth_probation('"+mDeviceID+"','"+packageName+"')|";
        NetUtils.post6(mUrl, sql, Auth.class, new Post6Listener<Auth>() {
            @Override
            public void onFail(Exception e) {
                getActivity().runOnUiThread(() -> {
                    ToastUtils.show(e+"");
                    mPb.setVisibility(View.GONE);
                });
            }

            @Override
            public void onSuccess(List<Auth> list) {
                if(list.size()<=0){
                    getActivity().runOnUiThread(() -> {
                        mTvProbation.setText("该设备己注册过，请联系软件供应商");
                        mPb.setVisibility(View.GONE);
                    });
                    return;
                }
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                new Thread(() -> {
//                    mDb.authDao().deleteAll();
//                    mDb.authDao().insert(list);
                    String closedate = list.get(0).getClosedate();
                    try {
                        Date date = dateFormat.parse(closedate);
                        getActivity().runOnUiThread(() -> ToastUtils.show("试用成功，截止日期："+dateFormat.format(date)));
                        dismiss();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }).start();
            }
        });
    }
}
